<template>
  <el-card>
    <div>
      <div v-for="p in state" :key="p.id">
        <div class="all">
          <el-checkbox
            v-model="p.checkAll"
            :indeterminate="p.indeterminate"
            @change="checkAllChange(p)"
            >{{ p.name }}</el-checkbox
          >
        </div>
        <el-checkbox-group v-model="p.checkeds" @change="gourpChange(p)">
          <el-checkbox v-for="c in p.children" :key="c.id" :label="c.id">{{
            c.name
          }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="flex">
        <el-button>清空</el-button>
        <el-button type="primary" @click="clickHandle">确定</el-button>
      </div>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getAllResourceListApi,
  getResourceListApi,
  resourceCategoryAllApi,
  allocResourceApi,
} from "./api/api";

const route = useRoute();
type IState = IResourceCategoryModel & {
  children: IResourceModel[];
  checkeds: number[];
  // 全选
  checkAll: boolean;
  // 半选
  indeterminate: boolean;
};
const router = useRouter();

let state = ref<IState[]>([]);
if (route.query.id) {
  Promise.all([
    resourceCategoryAllApi(),
    getAllResourceListApi(),
    getResourceListApi(parseInt(route.query.id as string)),
  ])
    .then((res) => {
      console.log(res);

      state.value = res[0].data.map((item) => ({
        ...item,
        children: [],
        checkeds: [],
        checkAll: false,
        indeterminate: false,
      }));
      res[1].data.forEach((resource) => {
        // console.log(resource);

        const cate = state.value.find(
          (cate) => cate.id === resource.categoryId
        );
        cate && cate.children.push(resource);
        // console.log(cate?.children);
      });
      res[2].data.forEach((item) => {
        // console.log(item);

        const pp = state.value.find((p) => p.id === item.categoryId);
        pp?.checkeds.push(item.id);
        console.log(pp?.checkeds);
      });
      state.value.forEach((pp) => {
        // 处理全选
        pp.checkAll = pp.checkeds.length === pp.children.length;
        // 处理半选
        pp.indeterminate =
          pp.checkeds.length > 0 && pp.checkeds.length < pp.children.length;
      });
    })
    .catch(() => {});
}
const checkAllChange = (data: IState) => {
  if (!data.checkAll) {
    data.checkeds = [];
  } else {
    data.checkeds = data.children.map((item) => item.id);
    // console.log(data.checkeds);
  }
  // 处理半选
  data.indeterminate =
    data.checkeds.length > 0 && data.checkeds.length < data.children.length;
};

const gourpChange = (data: IState) => {
  // 处理全选
  data.checkAll = data.checkeds.length === data.children.length;
  // 处理半选
  data.indeterminate =
    data.checkeds.length > 0 && data.checkeds.length < data.children.length;
};
console.log(state.value);

// 确定按钮
const clickHandle = () => {
  allocResourceApi({
    roleId: parseInt(route.query.id as string),
    // 把所有勾选的id发回服务器
    resourceIds: state.value.reduce<number[]>((prev, next) => {
      return prev.concat(next.checkeds);
    }, []),
  });
  ElMessageBox.confirm("确定保存修改吗？", "分配资源", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      ElMessage.success("添加成功");
      router.push("/ums/role");
    })
    .catch(() => {});
};
</script>
<style lang="less" scoped>
.all {
  padding: 20px;
  background-color: #f2f6fc;
}
:deep(.el-checkbox-group) {
  display: grid;
  grid-template-columns: repeat(3, 33%);
  padding: 20px;
}
.flex {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>
